<template>
  <!-- 添加或修改设备对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="500px" append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="90px">

      <!-- 设备ID -->
      <el-form-item label="设备ID" prop="id">
        <el-input v-model="form.id" :disabled="isUpdate" placeholder="请输入设备ID"/>
      </el-form-item>

      <!-- 设备名称 -->
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
      </el-form-item>

      <!-- 产品名称 -->
      <el-form-item label="所属产品" prop="productId">
        <el-select v-model="form.productId" :disabled="isUpdate" placeholder="请选择所属产品" class="select-width">
          <el-option
            v-for="dict in productList"
            :key="dict.id"
            :label="dict.productName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <div v-if="deviceType !== 'childrenDevice'">
        <!-- 绑定服务 -->
        <el-form-item>
          <span slot="label">
            <el-tooltip>
              <div slot="content">
                自动绑定：设备上报数据自动绑定服务；<br/>
                手动绑定：配置ip地址和端口号绑定已存在的服务；<br/>
                什么情况需要手动绑定？1.设备不会主动推送数据，2.无法通过数据认证设备
              </div>
              <i class="el-icon-question"></i>
            </el-tooltip>
            绑定服务
          </span>
          <el-select v-model="serviceBindTypeValue" :disabled="!isNotActive" class="select-width">
            <el-option
              v-for="item in serviceBindType"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- ip -->
        <el-form-item v-if="ipVisible" label="IP地址" prop="ip">
          <el-input v-model="form.ip" :disabled="!isNotActive" placeholder="请输入ip地址"/>
        </el-form-item>

        <!-- port -->
        <el-form-item v-if="portVisible" label="端口号" prop="port">
          <el-input v-model="form.port" :disabled="!isNotActive" placeholder="请输入端口号"/>
        </el-form-item>
      </div>

      <!-- 所属机构 -->
      <!--
      <el-form-item label="所属机构" prop="groupId">
        <el-select v-model="form.groupId" placeholder="请选择所属机构" class="select-width">
          <el-option
            v-for="dict in groupId"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      -->

      <!-- 说明 -->
      <el-form-item label="说明" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { addDevice, getDevice, updateDevice } from '@/api/iot/device'
import { queryProduct } from '@/api/iot/product'

export default {
  name: 'DeviceAddEdit',
  data() {
    return {
      //判断需要发的请求是新增还是修改
      type: null,
      //产品列表
      productList: [],
      // 设备类型
      deviceType: undefined,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否是更新操作
      isUpdate: false,
      // 查询参数
      queryParams: {
        publishState: null
      },
      // 表单参数
      form: {
        configuration: {}
      },
      // 服务绑定类型，默认自动绑定
      serviceBindTypeValue: 'auto',
      // 服务绑定类型
      serviceBindType: [
        {
          value: 'auto',
          name: '自动绑定'
        },
        {
          value: 'manual',
          name: '手动绑定'
        }
      ],
      ipVisible: false,
      portVisible: false,
      // 表单校验
      rules: {
        id: [
          { required: true, message: '请输入设备ID', trigger: 'blur' }
        ],
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        ip: [
          { required: true, validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入IP地址'))
                return
              }
              const ipPattern = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
              if (!ipPattern.test(value)) {
                callback(new Error('请输入正确的IP地址'))
                return
              }
              callback()
            }, trigger: 'change' }
        ],
        port: [
          { required: true, validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入端口号'))
                return
              }
              const portPattern = /^([1-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
              if (!portPattern.test(value)) {
                callback(new Error('请输入正确的端口号'))
                return
              }
              callback()
            },
            trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    address: {
      get() {
        const ip = this.form.ip
        const port = this.form.port
        if (!ip || !port) {
          return ''
        }
        return `/${ip}:${port}`
      },
      set(addr) {
        if (addr) {
          const addrArray = addr.split(/[:/]/)
          this.$set(this.form, 'ip', addrArray[1])
          this.$set(this.form, 'port', addrArray[2])
        }
      }
    },
    isNotActive() {
      const deviceState = this.form.deviceState
      if (!deviceState) {
        return true
      }
      return deviceState === 'notActive'
    }
  },
  watch: {
    serviceBindTypeValue(type) {
      if (this.serviceBindType[0].value === type) {
        this.form.ip = undefined
        this.form.port = undefined
        this.ipVisible = false
        this.portVisible = false
        return
      }
      if (this.serviceBindType[1].value === type) {
        this.ipVisible = true
        this.portVisible = true
      }
    },
    'form.productId'(productId) {
      const filterData = this.productList.filter(item => item.id === productId)
      if (filterData.length > 0) {
        this.deviceType = filterData[0].deviceType
      }
    }
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        configuration: {},
        gatewayDevice: null,
        productId: null,
        groupId: null,
        deviceName: null,
        deviceCode: null,
        deviceState: null,
        features: null,
        description: null,
        registryTime: null,
        createTime: null,
        updateTime: null,
        // 需要添加ip和port不然表单绑定会失效，无法输入数据
        ip: null,
        port: null
      }
      this.resetForm('form')
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.serviceBindTypeValue = this.serviceBindType[0].value
      this.isUpdate = false
      this.reset()
      queryProduct(this.queryParams).then(response => {
        this.productList = response.data
      })
      this.type = 1
      this.open = true
      this.title = '添加设备'
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset()
      this.isUpdate = true
      this.type = 0
      queryProduct(this.queryParams).then(response => {
        this.productList = response.data
        getDevice(id).then(response => {
          this.form = response.data
          if (this.form.address) {
            this.serviceBindTypeValue = this.serviceBindType[1].value
            this.address = this.form.address
          }
          this.open = true
          this.title = '修改设备'
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.address = this.address
          if (this.type === 0) {
            updateDevice(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.$emit('update')
            })
          } else {
            this.form.configuration = JSON.stringify(this.form.configuration)
            addDevice(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.$emit('update')
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
